package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.StringRes;
import android.support.design.widget.FloatingActionButton;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sam.im.heiqun.entities.ImageSendEntity;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.widgets.imagepicker.MediaConfig;
import com.sam.im.heiqun.widgets.imagepicker.MediaFile;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.github.angads25.filepicker.controller.DialogSelectionListener;
import com.github.angads25.filepicker.model.DialogConfigs;
import com.github.angads25.filepicker.model.DialogProperties;
import com.github.angads25.filepicker.view.FilePickerDialog;
import com.iflytek.sunflower.FlowerCollector;
import com.melink.bqmmsdk.ui.keyboard.BQMMKeyboard;
import com.melink.bqmmsdk.widget.BQMMEditView;
import com.melink.bqmmsdk.widget.BQMMSendButton;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.callmain.Maincallactivity;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.uis.adapters.ExpressionAdapter;
import com.sam.im.heiqun.uis.widgets.ChatBottomView;
import com.sam.im.heiqun.uis.widgets.ChatBottomViews;
import com.sam.im.heiqun.uis.widgets.ExpandGridView;
import com.sam.im.heiqun.uis.widgets.HeadIconSelectorView;
import com.sam.im.heiqun.uis.widgets.MediaManager;
import com.sam.im.heiqun.uis.widgets.pulltorefresh.PullToRefreshLayout;
import com.sam.im.heiqun.utils.FileSaveUtil;
import com.sam.im.heiqun.utils.ImageCheckoutUtil;
import com.sam.im.heiqun.utils.KeyBoardUtils;
import com.sam.im.heiqun.utils.MIUIUtils;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.PersimmionsUtils;
import com.sam.im.heiqun.utils.PictureUtil;
import com.sam.im.heiqun.utils.SmileUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.utils.XFAudioUtil;
import com.sam.im.heiqun.view.RecordButton;
import com.yuyh.library.audiovideo.Utils;
import com.yuyh.library.audiovideo.VideoRecorderActivity;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.ScreenUtil;
import com.yuyh.library.utils.data.safe.MD5;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * other_lv
 * Created by Joe on 2017/1/7.
 */
public abstract class ChatBaseActivity extends BaseSwipeBackActivity {
//public abstract class ChatBaseActivity extends BaseHeaderActivity {

    private static final String TAG = ChatBaseActivity.class.getSimpleName();
    public PullToRefreshLayout pullList;
    public boolean isDown = false;
    private boolean CAN_WRITE_EXTERNAL_STORAGE = true;
    protected static final int SMALL_VEDIO = 2131;
    private boolean CAN_RECORD_AUDIO = true;
    public int position; //加载滚动刷新位置
    public int bottomStatusHeight = 0;
    public int listSlideHeight = 0;//滑动距离
    public ImageView emoji;
    public ImageView mess_iv;
    public ImageView voiceIv;
    public BQMMSendButton sendBtn;
    public ChatBottomViews tbbv;
    //    public AudioRecordButton voiceBtn;
    public RecordButton voiceBtn;
    public BQMMEditView mEditTextContent;
    //public ViewPager expressionViewpager;
    //public LinearLayout emoji_group;
    private File mCurrentPhotoFile;
    public View activityRootView;
    private Toast mToast;
    private RelativeLayout relative;
    private String permissionInfo;
    //    private String camPicPath;
    public List<ImMessage> tblist = new ArrayList<>();
    private List<String> reslist;
    public int page = 0;
    public int number = 15;
    public List<ImMessage> pagelist = new ArrayList<>();
    public ArrayList<ImageInfoBean> imageList = new ArrayList<>();//adapter图片数据
    public HashMap<Integer, Integer> imagePosition = new HashMap<Integer, Integer>();//图片下标位置
    private static final int SDK_PERMISSION_REQUEST = 127;
    private static final int SDK_PERMISSION_REQUEST_UTIL = 128;
    private static final int IMAGE_SIZE = 300 * 1024;// 300kb//这里有个坑，在压缩的时候，PictureUtils中MAXSIZEKB也是大小限制，需统一
    public static final int SEND_OK = 0x1110;
    public static final int REFRESH = 0x0011;
    public static final int REFRESH_FANYI = 0x0012;
    public static final int RECERIVE_OK = 0x1111;
    public static final int PULL_TO_REFRESH_DOWN = 0x0111;
    public String fromid = "0";
    public long destid = 0;
    private static final int RESULT_RED_PACKET_SEND = 101;
    public int state = 0;//0表示正常1：表示表情弹起；2：表示其他选择弹起
    private Uri imageUri;
    public FloatingActionButton speakerBt;
    private Bitmap bitmap;
    public BQMMKeyboard bqmmKeyboard;
    public String friendheadurl;

    /**
     * 发送文本消息
     */
    protected abstract void sendMessage();

    /**
     * 发送图片文件
     */
    protected abstract void sendImage(ImageSendEntity imageSendEntity);

    /**
     * 发送文件
     */
    protected abstract void sendFile(String filepath);

    /**
     * 发送语音消息
     *
     * @param seconds
     * @param filePath
     */
    protected abstract void sendVoice(float seconds, String filePath);

    /**
     * 撤回消息
     */
    protected abstract void withdrawMsg(long msgid);

//    /**
//     * 发送视屏通话
//     */
//    protected abstract void sendCallVideo(String content);

    /**
     * 发送语音通话
     */
    protected abstract void sendCallVoice();

    /**
     * 发送语音通话
     */
    protected abstract void sendCallVideo();

    /**
     * 发送小视屏
     *
     * @param
     */
    protected abstract void sendVedio(VedioEntity vedioEntity);

    /**
     * 发送位置
     *
     * @param imgFile
     * @param address
     */
    protected abstract void sendLocation(File imgFile, String address, double lat, double lut);

    /**
     * 发送阅后即焚
     */
    protected abstract void sendReadDelete(File imgfile);

    /**
     * AA收款
     */
    protected abstract void sendAAcollection(String nums, String money, String discrible, String amt);

    protected abstract void loadRecords();

    private PersimmionsUtils persimmionsUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        EventBus.getDefault().register(this);//订阅
        EventBus.getDefault().post(Constant.CLOSE_CHAT_GROUP_ACTIVITY);
        findView();
        init();
        getPersimmions();
        initPersimmions();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        findView();
//        init();
//    }

    @Override
    protected void onNewIntent(Intent intent) {
        pagelist.clear();
        imageList.clear();
        tblist.clear();
        super.onNewIntent(intent);
        setIntent(intent);
        getTitleText();
        init();
    }

    @Override
    protected void onDestroy() {
        MediaManager.pause();
        MediaManager.release();
        cancelToast();
//        if (voiceBtn != null) {
//            voiceBtn.mAudioManager.setOnAudioStageListener(null);
//        }
//        EventBus.getDefault().unregister(this);//解除订阅
        if (bitmap != null) {
            bitmap.recycle();
        }
        super.onDestroy();
    }

    protected void findView() {
        pullList = (PullToRefreshLayout) findViewById(R.id.content_lv);
        activityRootView = findViewById(R.id.layout_tongbao_rl);
        mEditTextContent = (BQMMEditView) findViewById(R.id.mess_et);
        mess_iv = (ImageView) findViewById(R.id.mess_iv);
        emoji = (ImageView) findViewById(R.id.emoji);
        voiceIv = (ImageView) findViewById(R.id.voice_iv);
        // expressionViewpager = (ViewPager) findViewById(R.id.vPager);
        voiceBtn = (RecordButton) findViewById(R.id.voice_btn);

        // voiceBtn = (RecordButton) findViewById(R.id.voice_btn);
        // emoji_group = (LinearLayout) findViewById(R.id.emoji_group);
        sendBtn = (BQMMSendButton) findViewById(R.id.send_btn);
        tbbv = (ChatBottomViews) findViewById(R.id.other_lv);
        speakerBt = (FloatingActionButton) findViewById(R.id.float_speaker_button);
        bqmmKeyboard = (BQMMKeyboard) findViewById(R.id.chat_msg_input_box);
        tbbv.callvideo.setVisibility(View.GONE);
        tbbv.setEnabled(false);
        tbbv.setEnabled(true);

        voiceBtn.setSavePath(FileSaveUtil.getVoicePath());//设置存储路径,6.0注意申请权限
        voiceBtn.setSaveName(UUID.randomUUID().toString() + ".amr");//设置文件名字，如果设置了名字，将会一直使用，后面的录音文件会覆盖前面的文件
        voiceBtn.setPrefix("heiqun");//设置文件名前缀，不设置名字，只设置前缀，保证文件不重复，存带前缀标志
        voiceBtn.setMaxIntervalTime(61000);//毫秒，设置最长时间
        voiceBtn.setMinIntervalTime(1000);//毫秒，设置最短录音时间
        voiceBtn.setTooShortToastMessage(getResources().getString(R.string.luyin_no1)); //设置时间太短的提示语
        relative = (RelativeLayout) findViewById(R.id.layout_tongbao_rl);
    }

    protected void init() {
        page = (int) getPages(number);
        // mEditTextContent.setOnKeyListener(onKeyListener);
        // mEditTextContent.requestFocus();
        PullToRefreshLayout.pulltorefreshNotifier pullNotifier = new PullToRefreshLayout.pulltorefreshNotifier() {
            @Override
            public void onPull() {
                downLoad();
            }
        };
        pullList.setpulltorefreshNotifier(pullNotifier);
        voiceIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                state = 0;
                Log.i(TAG, "onClick: ---语音切换按钮点击--001--");
                if (voiceBtn.getVisibility() == View.GONE) {
                    Log.i(TAG, "onClick: ---语音切换按钮点击--002--");
                    persimmionsUtils.getPersimmions(7, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE});
                } else {
                    Log.i(TAG, "onClick: ---语音切换按钮点击--003--");
                    mEditTextContent.setVisibility(View.VISIBLE);
                    voiceBtn.setVisibility(View.GONE);
                    voiceIv.setImageResource(R.drawable.voice_btn_normal);
                    KeyBoardUtils.showKeyBoard(ChatBaseActivity.this, mEditTextContent);

                    String string = mEditTextContent.getText().toString();
                    if (string.length() > 0) {
                        sendBtn.setVisibility(View.VISIBLE);
                        mess_iv.setVisibility(View.GONE);
                    }
                }
                Log.i(TAG, "onClick: ---语音切换按钮点击--004--");
            }

        });
        mess_iv.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                //  emoji_group.setVisibility(View.GONE);
                bqmmKeyboard.setVisibility(View.GONE);
                if (tbbv.getVisibility() == View.GONE) {
                    state = 2;
                    mEditTextContent.setVisibility(View.VISIBLE);
                    mEditTextContent.setFocusable(true);
                    voiceBtn.setVisibility(View.GONE);
                    emoji.setImageResource(R.drawable.emoji);
                    voiceIv.setImageResource(R.drawable.voice_btn_normal);
                    tbbv.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tbbv.setVisibility(View.VISIBLE);
                        }
                    }, 80);
                    mEditTextContent.requestFocus();
                    KeyBoardUtils.hideKeyBoard(ChatBaseActivity.this,
                            mEditTextContent);
                    mess_iv.setImageResource(R.drawable.chatting_setmode_keyboard_btn_normal);
                } else {
                    state = 0;
                    tbbv.setVisibility(View.GONE);
                    KeyBoardUtils.showKeyBoard(ChatBaseActivity.this, mEditTextContent);
                    mess_iv.setImageResource(R.drawable.tb_more);
                }
            }
        });

      /*  sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });*/
        loadRecords();
        tbbv.setOnHeadIconClickListener(new HeadIconSelectorView.OnHeadIconClickListener() {

            @SuppressLint("InlinedApi")
            @Override
            public void onClick(int from) {
                switch (from) {
                    case ChatBottomViews.FROM_CAMERA:

                        persimmionsUtils.getPersimmions(1, new String[]{Manifest.permission.CAMERA});

//                        if (!CAN_WRITE_EXTERNAL_STORAGE) {
//                            Toast.makeText(ChatBaseActivity.this, getResources().getString(R.string.premission_no_open_please_set_open_photo_permission), Toast.LENGTH_SHORT).show();
//                        } else {
//                            final String state = Environment.getExternalStorageState();
//                            if (Environment.MEDIA_MOUNTED.equals(state)) {
//                                Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                String imageName = System.currentTimeMillis() + ".jpg";
//                                String imagePath = Environment.getExternalStorageDirectory() + "/" + imageName;
//                                imageUri = Uri.fromFile(new File(imagePath));
//                                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                                startActivityForResult(captureIntent, 66);
//                            } else {
//                                showToast(getResources().getString(R.string.please_check_up_SD_card));
//                            }
//                        }
                        break;
                    case ChatBottomViews.FROM_FILE://文件
//                        persimmionsUtils.getPersimmions(2, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                        filepickerchose();
                        // chosefile();
                        break;
                    case ChatBottomViews.FROM_TRANSFER://转账
                        ImFriendEntivity mImFriendEntivity = ToolsUtils.getFriendById("" + destid);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("friendInfo", mImFriendEntivity);
                        bundle.putLong("destid", destid);
                        startActivityForResult(TransferAccountsActivity.class, ChatActivity.RESULT_TRANSFER_SEND, bundle);
                        break;
                    case ChatBottomViews.FROM_LOCATION://位置
                        persimmionsUtils.getPersimmions(3, new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
                        break;
                    case ChatBottomViews.FROM_REDPACKET://红包
//                        Bundle bundler = new Bundle();
//                        bundler.putLong("destid", destid);
//                        startActivityForResult(SendOrdinaryRedPacket.class, RESULT_RED_PACKET_SEND, bundler);
                        SendRedPacketSelectActivity.start(ChatBaseActivity.this, RESULT_RED_PACKET_SEND, destid, 0);
                        break;
                    case ChatBottomViews.FROM_GALLERY:
                       /* if (!CAN_WRITE_EXTERNAL_STORAGE) {
                            Toast.makeText(ChatBaseActivity.this, getResources().getString(R.string.premission_no_open_please_set_open_photo_permission), Toast.LENGTH_SHORT).show();
                        } else {
                            String status = Environment.getExternalStorageState();
                            if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                                Intent intent = new Intent();
                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
//                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    //     intent.putExtra("crop", "true");
                                    //       intent.putExtra("scale", "true");
                                    //       intent.putExtra("scaleUpIfNeeded", true);
                                }
                                intent.setType("image*//*");
                                startActivityForResult(intent,
                                        ChatBottomView.FROM_GALLERY);
                            } else {
                                showToast(getResources().getString(R.string.no_SD_card));
                            }
                        }*/
                        persimmionsUtils.getPersimmions(2, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE});
                        break;
                    case ChatBottomViews.FROM_VIDEIO://视屏
                        //startActivity(RecordVedioActivity.class);
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        persimmionsUtils.getPersimmions(4, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO});
//                        }else {
//                            // 录制
//                            File saveDir = null;
//                            saveDir = new File(FileSaveUtil.getSdCardPath()+"/easyVideo/","yunxin_"+System.currentTimeMillis());
//                            saveDir.mkdirs();
//
//                            VideoRecorderActivity.start(ChatBaseActivity.this, saveDir, Utils.videoMaxTime, SMALL_VEDIO);
//                        }

                       /* MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                               // .doH264Compress(new AutoVBRMode(30)
                      // .setVelocity(BaseMediaBitrateConfig.Velocity.SUPERFAST)
                            //    )
                                .setMediaBitrateConfig(new AutoVBRMode(18)
                       .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
                                )
                                .smallVideoWidth(480)
                                .smallVideoHeight(480)
                                .recordTimeMax(8 * 1000)
                                .maxFrameRate(20)
                                .captureThumbnailsTime(1)
                                .recordTimeMin((int) (1.5 * 1000))
                                .build();
                        MediaRecorderActivity.goSmallVideoRecorder(ChatBaseActivity.this,VideoPlayerActivity.class.getName(), config);*/
                        break;
                    case ChatBottomViews.FROM_AA://AA收款
                        startActivityForResult(SendAAActivity.class, ChatBottomView.FROM_AA);
                        break;
                    case ChatBottomViews.READ_DELETE://阅后即焚
                        persimmionsUtils.getPersimmions(5, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE});
                        break;
                    case ChatBottomViews.READ_CALLVIDEO: //视屏通话
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("type", "0");
                        bundle1.putString("headurl", friendheadurl);
                        bundle1.putString("userid", ToolsUtils.getMyUserId());
                        bundle1.putString("destid", destid + "");
                        App.rtcdestid = destid + "";
                        startActivityForResult(Maincallactivity.class, 10010, bundle1);
//                        sendCallVideo("1");
                        sendCallVideo();
                        break;
                    case ChatBottomViews.READ_CALLVOICE: //语音通话
                        sendCallVoice();
                        break;
                    case ChatBottomViews.FROM_COLACTION:
                        //收藏
                        Bundle bundle3 = new Bundle();
                        bundle3.putInt("tag", 1);
                        bundle3.putLong("destid", destid);
                        startActivityForResult(CollectionActivity.class, ChatBottomViews.FROM_COLACTION, bundle3);
                        break;
                    case ChatBottomViews.FROM_FRIENDMP:
                        //名片
                        Bundle bundle4 = new Bundle();
                        bundle4.putString("tags", "12");
                        startActivityForResult(SelecteLocalFriendActivity.class, ChatBottomViews.FROM_FRIENDMP, bundle4);
                        break;
                    case ChatBottomViews.FROM_AUDIO_TXT:
                        persimmionsUtils.getPersimmions(6, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE});
                        break;
                    case ChatBottomViews.FROM_VOICE_TXT:
                        //语音通话
                        sendCallVoice();
                        break;
                    case ChatBottomViews.FROM_VIDEO_TXT:
                        //视频通话
                        sendCallVideo();
                        break;
                }
            }

        });

        emoji.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                tbbv.setVisibility(View.GONE);
                if (bqmmKeyboard.getVisibility() == View.GONE) {
                    state = 1;
                    voiceBtn.setVisibility(View.GONE);
                    voiceIv.setImageResource(R.drawable.voice_btn_normal);
                    mess_iv.setImageResource(R.drawable.tb_more);
                    emoji.setImageResource(R.drawable.chatting_setmode_keyboard_btn_normal);
                    mEditTextContent.requestFocus();
                    KeyBoardUtils.hideKeyBoard(ChatBaseActivity.this,
                            mEditTextContent);
                    mEditTextContent.setVisibility(View.VISIBLE);
                    bqmmKeyboard.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            bqmmKeyboard.setVisibility(View.VISIBLE);
                        }
                    }, 80);
                } else {
                    state = 0;
                    bqmmKeyboard.setVisibility(View.GONE);
                    emoji.setImageResource(R.drawable.emoji);
                    KeyBoardUtils.showKeyBoard(ChatBaseActivity.this, mEditTextContent);
                }
            }
        });
        // 表情list
        reslist = getExpressionRes(35);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
        View gv1 = getGridChildView(1);
        View gv2 = getGridChildView(2);
        views.add(gv1);
        views.add(gv2);
        // expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
        mEditTextContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                state = 0;
                bqmmKeyboard.setVisibility(View.GONE);
                tbbv.setVisibility(View.GONE);
                emoji.setImageResource(R.drawable.emoji);
                mess_iv.setImageResource(R.drawable.tb_more);
                voiceIv.setImageResource(R.drawable.voice_btn_normal);
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(mEditTextContent, 0);
            }
        });
//        controlKeyboardLayout(activityRootView, pullList);
        bottomStatusHeight = ScreenUtil.getBottomStatusHeight(this);
        //加载本地聊天记录
        //  page = (int) mChatDbManager.getPages(number);

    }


    TextView mtitle;

    @Override
    protected void onResume() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onResume(ChatBaseActivity.this);
        FlowerCollector.onPageStart(TAG);
        super.onResume();
    }

    @Override
    protected void onPause() {
        // 开放统计 移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(ChatBaseActivity.this);
        super.onPause();
    }

    private void filepickerchose() {
        DialogProperties properties = new DialogProperties();
        properties.selection_mode = DialogConfigs.SINGLE_MODE;
        properties.selection_type = DialogConfigs.FILE_SELECT;
        properties.root = new File(DialogConfigs.DEFAULT_DIR);
        properties.error_dir = new File(DialogConfigs.DEFAULT_DIR);
        properties.offset = new File(DialogConfigs.DEFAULT_DIR);
        properties.extensions = new String[]{".txt", ".png", ".jpg", ".gif", ".jpeg", ".bmp", ".apk", ".mp3", ".mp4", ".pdf"};
        //properties.extensions = null;
        FilePickerDialog filedialog = new FilePickerDialog(ChatBaseActivity.this, properties);
        filedialog.setTitle(getResources().getString(R.string.select_file));
        filedialog.setNegativeBtnName(getResources().getString(R.string.cancel));
        filedialog.setPositiveBtnName(getResources().getString(R.string.ok));
        filedialog.show();

        filedialog.setDialogSelectionListener(new DialogSelectionListener() {
            @Override
            public void onSelectedFilePaths(String[] files) {
                if (files != null && files.length > 0) {
                    Log.i("info", "选择的文件路径==" + files[0]);
                    try {
                        String end = files[0].substring(files[0].lastIndexOf(".") + 1, files[0].length()).toLowerCase();
                        /* 依扩展名的类型决定MimeType */
                        if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                                end.equals("jpeg") || end.equals("bmp")) {
                            Log.i("info", "进来了");
                            Bitmap bitmap = PictureUtil.getSmallBitmap(files[0]);
                            bitmap = PictureUtil.reviewPicRotate(bitmap, files[0]);
                            File mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, files[0]);
                            if (mCurrentPhotoFile.exists()) {
                                int size = ImageCheckoutUtil.getImageSize(bitmap);
                                sendImage(new ImageSendEntity(mCurrentPhotoFile.getAbsolutePath(),true));
                            } else {
                                showToast(getResources().getString(R.string.this_file_nonentity));
                            }
                        } else {
                            sendFile(files[0]);
                        }
                        //File file = new File(realFilePath);
                        //Log.i("info","拿到的文件=="+realFilePath);
                    } catch (Exception e) {
                        showToast(getResources().getString(R.string.file_select_fail));
                    }
                }
            }
        });
    }

    private void chosefile() {
        if (!MIUIUtils.getSystem().equals(MIUIUtils.SYS_MIUI) && !MIUIUtils.getSystem().equals(MIUIUtils.SYS_EMUI)) {
            String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                Intent fileintent = new Intent();
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                    fileintent.setAction(Intent.ACTION_GET_CONTENT);
                } else {
                    fileintent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                    fileintent.addCategory(Intent.CATEGORY_OPENABLE);
                }
                fileintent.setType("*/*");
                startActivityForResult(fileintent,
                        ChatActivity.RESULT_SEND_FILE);
            } else {
                showToast(getResources().getString(R.string.no_SD_card));
            }
        } else {
            String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                Intent fileintent = new Intent();
                fileintent.setAction(Intent.ACTION_GET_CONTENT);
                fileintent.addCategory(Intent.CATEGORY_OPENABLE);
                fileintent.setType("*/*");
                startActivityForResult(Intent.createChooser(fileintent, ""), ChatActivity.RESULT_SEND_FILE);
            } else {
                showToast(getResources().getString(R.string.no_SD_card));
            }
        }
    }

    public long getPages(int number) {

        long count = ImMessage.count(ImMessage.class, "uniqueness=?", new String[]{fromid + "_" + destid});
        long page = count / number;
        if (page > 0 && count % number == 0) {
            return page - 1;
        }

        return page;
    }

    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 麦克风权限
            if (addPermission(permissions, Manifest.permission.RECORD_AUDIO)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 相机权限
            if (addPermission(permissions, Manifest.permission.CAMERA)) {
                permissionInfo += "Manifest.permission.CAMERA Deny \n";
            }
            //地理位置权限
            if (addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION)) {
                permissionInfo += "Manifest.permission.ACCESS_FINE_LOCATION Deny \n";
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    CAN_WRITE_EXTERNAL_STORAGE = false;
                    Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                            .show();
                }
                if (perms.get(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    CAN_RECORD_AUDIO = false;
                    Toast.makeText(this, getResources().getString(R.string.disable_record_will_make_voice_unusable), Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            case SDK_PERMISSION_REQUEST_UTIL:
                if (null != persimmionsUtils)
                    persimmionsUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void downLoad() {
        if (!isDown) {
            loadRecords();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            tbbv.setVisibility(View.GONE);
            mess_iv.setImageResource(R.drawable.tb_more);
            switch (requestCode) {
                case ChatBottomViews.READ_DELETE: {
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (null != stringArrayListExtra && stringArrayListExtra.size() > 0) {
                        for (int i = 0; i < stringArrayListExtra.size(); i++) {
                            String path = stringArrayListExtra.get(i);
                            Log.i("info", "返回的路径==" + path);
                            // Uri uri = data.getData();
                            // String path = FileSaveUtil.getPath(getApplicationContext(), uri);
                            try {
//                        Bitmap bitmap = PictureUtil.getBitmapFormUri(this, uri);
                                Bitmap bitmap = PictureUtil.getSmallBitmap(path);
                                if (bitmap == null) {
                                    assert path != null;
                                    mCurrentPhotoFile = new File(path); // 图片文件路径
                                } else {
                                    mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, path);
                                }
                                assert mCurrentPhotoFile != null;
                                if (mCurrentPhotoFile.exists()) {
                                    int size = ImageCheckoutUtil.getImageSize(ImageCheckoutUtil.getLoacalBitmap(path));
                                    float s = size / 8.0f / 1024;
                                    if (s > IMAGE_SIZE) {
                                        showDialog(path, true);
                                    } else {
                                        sendReadDelete(mCurrentPhotoFile);
                                    }
                                } else {
                                    showToast(getResources().getString(R.string.this_file_nonentity));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
                }
                case 66: {
                    String path = FileSaveUtil.getPath(getApplicationContext(), imageUri);
                    try {
//                        Bitmap bitmap = PictureUtil.getBitmapFormUri(this, imageUri);
                        Bitmap bitmap = PictureUtil.getSmallBitmap(path);
                        bitmap = PictureUtil.reviewPicRotate(bitmap, path);
                        mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, path);
                        if (mCurrentPhotoFile.exists()) {
                            int size = ImageCheckoutUtil.getImageSize(bitmap);
                            if (size > IMAGE_SIZE) {
                                showDialog(path, true);
                            } else {
                                sendImage(new ImageSendEntity(mCurrentPhotoFile.getAbsolutePath(),true));
                            }
                        } else {
                            showToast(getResources().getString(R.string.this_file_nonentity));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
                case ChatBottomView.FROM_GALLERY:
                    ArrayList<String> filePaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (filePaths == null || filePaths.isEmpty()) {
                        break;
                    }
                    boolean canSendToOther = data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_CAN_SEND_TO_OTHER, false);

                    for (String filePath : filePaths) {
                        MediaFile.MediaFileType mediaFileType = MediaFile.getFileType(filePath);
                        if (mediaFileType == null) {
                            continue;
                        }
                        boolean isImageFile = MediaFile.isImageFileType(mediaFileType.fileType);
                        if (isImageFile) {
                            sendImage(filePath,canSendToOther);
                        }
                        boolean isVideoFileType = MediaFile.isVideoFileType(mediaFileType.fileType);
                        if (isVideoFileType) {
                            sendVideo(filePath,canSendToOther);
                        }
                    }
                    break;
                case ChatBottomView.FROM_AA:
                    String nums = data.getStringExtra("nums");
                    String money = data.getStringExtra("money");
                    String discrible = data.getStringExtra("discrible");
                    String amt = data.getStringExtra("amt");
                    sendAAcollection(nums, money, discrible, amt);
                    break;
            }
        } else if (resultCode == CalldideoActivity.CALL_VIDEO_CANCLE) {//视屏取消
//            sendCallVideo("0");
            sendCallVideo();
        } else if (resultCode == CalldideoActivity.CALL_VIDEO_CANCLE_THE) {//中断视屏
//            sendCallVideo("2");
            sendCallVideo();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 界面复位
     */
    protected void reset() {
        bqmmKeyboard.setVisibility(View.GONE);
        tbbv.setVisibility(View.GONE);
        emoji.setImageResource(R.drawable.emoji);
        mess_iv.setImageResource(R.drawable.tb_more);
        voiceIv.setImageResource(R.drawable.voice_btn_normal);
    }

    public void showToast(String text) {
        if (mToast == null) {
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void showToast(@StringRes int textRes) {
        showToast(getResources().getString(textRes));
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }


    /**
     * 获取表情的gridview的子view
     *
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.layout_expression_gridview, null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
        final List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = reslist.subList(0, 27);
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(reslist.subList(27, reslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this,
                1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情
                    if (filename != "delete_expression") { // 不是删除键，显示表情
                        // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                        @SuppressWarnings("rawtypes")
                        Class clz = Class
                                .forName("com.sam.im.easyim.utils.SmileUtils");
                        Field field = clz.getField(filename);
                        String oriContent = mEditTextContent.getText()
                                .toString();
                        int index = Math.max(
                                mEditTextContent.getSelectionStart(), 0);
                        Log.i("info", "content==" + oriContent);
                        StringBuilder sBuilder = new StringBuilder(oriContent);
                        Spannable insertEmotion = SmileUtils.getSmiledText(
                                ChatBaseActivity.this,
                                (String) field.get(null));
                        Log.i("info", "index==" + index + " insertEmotion =" + insertEmotion.toString());
                        sBuilder.insert(index, insertEmotion);//插入字符串
                        String emojifilename = list.get(position);
                        //获取对应的图片 输入框实现文字表情混排
                        int resId = ChatBaseActivity.this.getResources().getIdentifier(emojifilename, "mipmap", ChatBaseActivity.this.getPackageName());
                        bitmap = BitmapFactory.decodeResource(getResources(), resId);
                        ImageSpan imageSpan = new ImageSpan(ChatBaseActivity.this, bitmap);
                        SpannableString spannableString = new SpannableString(insertEmotion.toString());
                        Log.i("info", "sbuilder==" + sBuilder.toString());
                        spannableString.setSpan(imageSpan, 0, insertEmotion.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        Log.i("info", "spannablestring==" + spannableString);
                        mEditTextContent.append(spannableString);
                        // mEditTextContent.setText(sBuilder.toString());
                        Log.i("info", "index==" + index + " insertEmotionsize =" + insertEmotion.length());
                        mEditTextContent.setSelection(index
                                + insertEmotion.length());//移动光标
                    } else { // 删除文字或者表情
                        if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                            int selectionStart = mEditTextContent
                                    .getSelectionStart();// 获取光标的位置
                            if (selectionStart > 0) {
                                String body = mEditTextContent.getText()
                                        .toString();
                                String tempStr = body.substring(0,
                                        selectionStart);
                                int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i,
                                            selectionStart);
                                    if (SmileUtils.containsKey(cs.toString()))
                                        mEditTextContent.getEditableText()
                                                .delete(i, selectionStart);
                                    else
                                        mEditTextContent.getEditableText()
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                } else {
                                    mEditTextContent.getEditableText().delete(
                                            selectionStart - 1, selectionStart);
                                }
                            }
                        }

                    }
                } catch (Exception e) {
                }

            }
        });
        return view;
    }

    public List<String> getExpressionRes(int getSum) {
        List<String> reslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {
            String filename = "f" + x;
            reslist.add(filename);
        }
        return reslist;

    }

    private void showDialog(final String path, final boolean canForward) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Bitmap bitmap = PictureUtil.compressSizeImage(path);
//                    bitmap = PictureUtil.rotateBitmap(bitmap,90);
                    mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, path);
                    if (mCurrentPhotoFile.exists()) {
                        int size = ImageCheckoutUtil.getImageSize(bitmap);
                        sendImage(new ImageSendEntity(mCurrentPhotoFile.getAbsolutePath(),canForward));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private String getSavePicPath() {
        final String dir = FileSaveUtil.getSdCardPath() + "image_data/";
        try {
            FileSaveUtil.createSDDirectory(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileName = String.valueOf(System.currentTimeMillis() + ".png");
        return dir + fileName;
    }

   /* public ImMessage getTbub(int version, int devType, int geoId, int type,
                             String msgId, long fromId, int fromType,
                             long destId, String content, int messageType,
                             long sendTime, long receiveTime, int status, String filePath, String uniqueness, float seconds, String imageIconUrl) {
        ImMessage tbub = new ImMessage();
        tbub.setVersion(version);
        String time = returnTime(sendTime);
        tbub.setDevType(devType);
        tbub.setUserVoiceTime(seconds);
        tbub.setType(type);
        tbub.setGeoId(geoId);
        tbub.setMsgId(msgId);
        tbub.setFromid(fromId);
        tbub.setFromType(fromType);
        //tbub.setFileUrl(content);
        tbub.setFilePath(filePath);
        //tbub.setUserVoicePath(content);
        tbub.setDestid(destId);
        if (content.equals("null")) {
            content = "null ";
        }
        tbub.setContent(content);
        tbub.setMessageType(messageType);
        tbub.setFromname(ToolsUtils.getUser().getNickName());//设置名字
        tbub.setSendTime(sendTime);
        tbub.setReceiveTime(receiveTime);
        tbub.setStatus(status);
        tbub.setUniqueness(uniqueness);
        tbub.setSendState(Constant.SENDING);
        tbub.setImageIconUrl(imageIconUrl);
        return tbub;
    }*/


    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                sendMessage();
                return true;
            }
            return false;
        }
    };

    @SuppressLint("SimpleDateFormat")
    public static String returnTime(long time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(time);
        return date;
    }


    /**
     * 初始化权限管理
     */
    private void initPersimmions() {
        persimmionsUtils = new PersimmionsUtils(ChatBaseActivity.this, new PersimmionsUtils.PersimmionsListener() {
            @Override
            public void OnPersimmionsSuccess(int type) {
                switch (type) {
                    case 1:
                        final String state = Environment.getExternalStorageState();
                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            String imageName = System.currentTimeMillis() + ".jpg";
                            String imagePath = Environment.getExternalStorageDirectory() + "/" + imageName;
                            imageUri = Uri.fromFile(new File(imagePath));
                            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                            startActivityForResult(captureIntent, 66);
                        } else {
                            showToast(getResources().getString(R.string.please_check_up_SD_card));
                        }
                        break;
                    case 2:
                        PhotoPickerIntent photointent = new PhotoPickerIntent(ChatBaseActivity.this);
                        photointent.setSelectModel(SelectModel.MULTI);
                        photointent.setShowCarema(false); // 是否显示拍照， 默认false
                        photointent.setMaxTotal(9);
                        photointent.showChooseForward(true);
                        MediaConfig mediaConfig = new MediaConfig();
                        mediaConfig.loadVideos = true;
                        photointent.setImageConfig(mediaConfig);
                        startActivityForResult(photointent, ChatBottomView.FROM_GALLERY);
                        break;
                    case 3:
                        ImFriendEntivity mImFriendEntivity2 = ToolsUtils.getFriendById("" + destid);
                        Bundle bundle2 = new Bundle();
                        bundle2.putSerializable("friendInfo", mImFriendEntivity2);
                        bundle2.putLong("destid", destid);
                        startActivityForResult(LocationActivity.class, ChatActivity.RESULT_LOCATION, bundle2);
                        break;
                    case 4:

//                        persimmionsUtils.getPersimmions(4,new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO});

                        // 录制
                        File saveDir = null;
                        saveDir = new File(FileSaveUtil.getSdCardPath() + "/easyVideo/", "yunxin_" + System.currentTimeMillis());
                        saveDir.mkdirs();

                        VideoRecorderActivity.start(ChatBaseActivity.this, saveDir, Utils.videoMaxTime, SMALL_VEDIO);

                        break;
                    case 5:
                        PhotoPickerIntent pt = new PhotoPickerIntent(ChatBaseActivity.this);
                        pt.setSelectModel(SelectModel.MULTI);
                        pt.setShowCarema(true); // 是否显示拍照， 默认false
                        pt.showChooseForward(true);
                        pt.setMaxTotal(1); // 最多选择照片数量，默认为9
                        mediaConfig = new MediaConfig();
                        mediaConfig.loadVideos = true;
                        pt.setImageConfig(mediaConfig);
                        startActivityForResult(pt, ChatBottomViews.READ_DELETE);
                        break;
                    case 6:
                        final XFAudioUtil xfAudioUtil = new XFAudioUtil(ChatBaseActivity.this, new XFAudioUtil.AudioClickListener() {
                            @Override
                            public void onResult(String result) {
                                Log.i(TAG, "onResult: =====语音听写结果======result=" + result);
                                if (null != mtitle) mtitle.setText(result);
                            }
                        });
                        MyDialog.ShowAudioTxtDialog(ChatBaseActivity.this, new MyDialog.DialogAudioClickListener() {
                            @Override
                            public void onstart() {
                                Log.i(TAG, "onstart: ----------------");
                                xfAudioUtil.start();
                            }

                            @Override
                            public void onend(TextView title) {
                                mtitle = title;
                                Log.i(TAG, "onend: ----------------");
                                xfAudioUtil.stop();
                            }

                            @Override
                            public void onok(String result) {
                                Log.i(TAG, "onok: ----------------");
                                mEditTextContent.setText(result);
                            }
                        });
                        break;
                    case 7:
                        emoji.setImageResource(R.drawable.emoji);
                        mess_iv.setImageResource(R.drawable.tb_more);
                        mEditTextContent.setVisibility(View.GONE);
                        //  emoji_group.setVisibility(View.GONE);
                        bqmmKeyboard.setVisibility(View.GONE);
                        tbbv.setVisibility(View.GONE);
                        voiceBtn.setVisibility(View.VISIBLE);
                        KeyBoardUtils.hideKeyBoard(ChatBaseActivity.this,
                                mEditTextContent);
                        voiceIv.setImageResource(R.drawable.chatting_setmode_keyboard_btn_normal);

                        sendBtn.setVisibility(View.GONE);
                        mess_iv.setVisibility(View.VISIBLE);
                        break;
                }

            }

            @Override
            public void OnPersimmionsFail(int type, int pos, String persimmion) {
                showToast(getResources().getString(R.string.no_pawr_nouse));
            }
        });
    }

    private void sendVideo(String videoPath,boolean canForward){

        Cursor query = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Video.Media.DURATION,
                        MediaStore.Video.Media._ID},
                MediaStore.Video.Media.DATA + "=?",
                new String[]{videoPath}, null);
        if (query != null) {

            if (query.moveToNext()) {

                int duration = query.getInt(query.getColumnIndex(MediaStore.Video.Media.DURATION));
                String id = query.getString(query.getColumnIndex(MediaStore.Video.Media._ID));

                String thumbPath = null;
                Cursor thumbCursor = getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Video.Thumbnails.DATA, MediaStore.Video.Thumbnails.VIDEO_ID},
                        MediaStore.Video.Thumbnails.VIDEO_ID + "=?",
                        new String[]{id},
                        null);
                if (thumbCursor != null) {
                    if (thumbCursor.moveToNext()) {
                        thumbPath = thumbCursor.getString(thumbCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                    }
                    thumbCursor.close();
                }
                if(thumbPath == null){
                    Bitmap  thumbBitmap = MediaFile.getVideoThumbnail(videoPath);
                    if(thumbBitmap != null){
                        thumbPath = new File(getCacheDir(), MD5.MD516(videoPath) + ".jpg").getAbsolutePath();
                        File file = PictureUtil.bitmapToFileJPG(thumbBitmap, thumbPath);
                        if(file == null || !file.exists()){
                            showToast(R.string.create_thumb_fail);
                            return;
                        }
                    }
                }

                VedioEntity vedioEntity = new VedioEntity();
                vedioEntity.setVedioPath(videoPath);
                vedioEntity.setVedioSize(duration);
                vedioEntity.setVedioBitmappath(thumbPath);
                vedioEntity.setCanForward(canForward);
                sendVedio(vedioEntity);
            }
            query.close();
        }
    }

    private void sendImage(String filePath,boolean canForward){

        if(TextUtils.isEmpty(filePath)){
            return;
        }
        Log.i("info", "返回的路径==" + filePath);
        try {
            Bitmap bitmap = PictureUtil.getSmallBitmap(filePath);
            bitmap = PictureUtil.reviewPicRotate(bitmap, filePath);
            if (bitmap == null) {
//                                Log.i(TAG, "onActivityResult: ---------图片的bitmap为空null-------000-------------");
                mCurrentPhotoFile = new File(filePath); // 图片文件路径
            } else {
//                                Log.i(TAG, "onActivityResult: ---------图片的bitmap不为空null-------0001-------------");
//                                mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, path);
                mCurrentPhotoFile = PictureUtil.bitmapToFileJPG(bitmap, filePath);
//                                Log.i(TAG, "onActivityResult: ---------图片的bitmap不为空null-------0002-------------");
            }
            if (mCurrentPhotoFile == null) {
                return;
            }
            if (mCurrentPhotoFile.exists()) {
                int size = ImageCheckoutUtil.getImageSize(ImageCheckoutUtil.getLoacalBitmap(filePath));
                float s = size / 8.0f / 1024;
                if (s > IMAGE_SIZE) {
//                                    Log.i(TAG, "onActivityResult: ----------图片过大----------");
                    showDialog(filePath,canForward);
                } else {
                    sendImage(new ImageSendEntity(mCurrentPhotoFile.getAbsolutePath(),canForward));
                }
            } else {
                showToast(getResources().getString(R.string.this_file_nonentity));
            }
        } catch (Exception e) {
            Log.i("info", filePath + "该图片已损坏");
            e.printStackTrace();
        }
    }
}
